package com.hundsun.aitest.util;
import java.util.Stack;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class JsonContentExtractor {

    //private static final Pattern JSON_CONTENT_PATTERN = Pattern.compile("\\{.*?\\}", Pattern.DOTALL);
    //private static final Pattern JSON_CONTENT_PATTERN = Pattern.compile("\\{(?:[^{}]|(?R))*?\\}", Pattern.DOTALL);
    private static final Pattern REPEAT_PATTERN = Pattern.compile("(\"[a-zA-Z]\"\\.repeat\\([0-9]+\\))");

    /**
     * 从给定的字符串中提取JSON内容。
     *
     * @param jsonString 包含JSON内容的输入字符串
     * @return 提取的JSON内容或如果没有找到有效的JSON则返回空字符串
     */
    public static String extractJsonContent(String jsonString) {
        StringBuilder jsonPart = new StringBuilder();
        Stack<Character> stack = new Stack<>();
        //如果有多个json，取最后一个
        String lastJsonContent = "";
        for (char c : jsonString.toCharArray()) {
            if (c == '{') {
                if (stack.isEmpty()) {
                    jsonPart = new StringBuilder();
                }
                stack.push(c);
                jsonPart.append(c);
            } else if (c == '}') {
                if (!stack.isEmpty()) {
                    stack.pop();
                    jsonPart.append(c);
                    if (stack.isEmpty()) {
                        // 更新最后一个找到的JSON内容
                        lastJsonContent = jsonPart.toString();
                    }
                }
            } else if (!stack.isEmpty()) {
                // 只有在已经开始记录JSON部分时才添加字符
                jsonPart.append(c);
            }
        }

        if (!lastJsonContent.isEmpty()) {

            lastJsonContent = replaceRepeatedChars(lastJsonContent);
            //JSON 字符串，可能包含单行注释。
            lastJsonContent.replaceAll("(?m)//.*", "");
            // 移除Markdown代码块标记
            lastJsonContent = lastJsonContent.replaceAll("^```json|```$", "").trim();

        } else {
            System.err.println("No valid JSON found in the input.");
        }

        return lastJsonContent;
    }
//    public static String extractJsonContent(String jsonString) {
//
//        Matcher matcher = JSON_CONTENT_PATTERN.matcher(jsonString);
//        //如果有多个json，取最后一个
//        String lastJsonContent = "";
//
//        while (matcher.find()) {
//            lastJsonContent = matcher.group(0);
//        }
//
//        if (!lastJsonContent.isEmpty()) {
//
//            lastJsonContent = replaceRepeatedChars(lastJsonContent);
//            //JSON 字符串，可能包含单行注释。
//            lastJsonContent.replaceAll("(?m)//.*", "");
//            // 移除Markdown代码块标记
//            lastJsonContent = lastJsonContent.replaceAll("^```json|```$", "").trim();
//
//        } else {
//            System.err.println("No valid JSON found in the input.");
//        }
//
//        return lastJsonContent;
//    }

    /**
     * 在JSON字符串中替换重复字符表达式为实际的重复字符。
     *
     * @param jsonString 包含重复字符表达式的JSON字符串
     * @return 替换了重复字符的JSON字符串
     */
    public static String replaceRepeatedChars(String jsonString) {
        Matcher matcher = REPEAT_PATTERN.matcher(jsonString);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String match = matcher.group(1);
            String charPart = match.substring(1, 2); // Get the character
            int repeatCount = Integer.parseInt(match.substring(match.indexOf('(') + 1, match.indexOf(')')));

            StringBuilder replacement = new StringBuilder();
            for (int i = 0; i < repeatCount; i++) {
                replacement.append(charPart);
            }
            String quotedReplacement = "\"" + replacement.toString() + "\"";
            matcher.appendReplacement(sb, Matcher.quoteReplacement(quotedReplacement));
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    /**
     * 从给定的字符串中提取JSON数组内容，并将其转换为Java对象列表。
     * @param rawContent: ai返回的内容，必须要求按json格式返回
     * @return : 提取的JSON数组内容，如果未找到则返回null
     */
    public static List<Map<String, String>> extractContentToList(String rawContent) {
        // 正则表达式匹配JSON数组
        String regex = "\\[[^\\[\\]]*\\]";
        Pattern pattern = Pattern.compile(regex, Pattern.DOTALL| Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(rawContent);

        if (matcher.find()) {
            String jsonString = matcher.group();
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                // 将JSON字符串转换为Java对象列表
                List<Map<String, String>> jsonList = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, String>>>(){});
                // 打印提取的JSON数组
                log.info("Extracted JSON array: {}", jsonList);
                return jsonList;
            } catch (IOException e) {
                e.printStackTrace();
                log.error("Extracted JSON array error: {}", e.toString());
            }
        } else {
            log.warn("No JSON array found in the text.");
        }
        return null;
    }
}